<!--
 * @Author: your name
 * @Date: 2021-11-09 13:22:40
 * @LastEditTime: 2021-11-29 20:19:44
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jingfeng-web\src\components\notice\notice.vue
-->
<template>
  <div class="app-notice">
    <div class="marquee-container">
      <marquee class="app-marquee" width="100%">{{ connectText }}</marquee>

      <el-button class="notice-btns" @click="lookForAnnouncement" type="text">查看记录</el-button>
      <el-avatar
        shape="square"
        fit="contain"
        size="small"
        class="notice-icons"
        :src="require('../../assets/image/icon/notice.png')"
      ></el-avatar>
    </div>
    <el-dialog
      :destroy-on-close="true"
      :close-on-click-modal="false"
      title="公告"
      width="75%"
      :visible.sync="announcementDialogVisible"
      class="commondialog"
    >
      <div class="commonbody">
        <div class="messageReminderContent" v-for="(item, index) in messageOutput" :key="index">
          <div class="messaageContent">
            {{ item.announcementContent }}
          </div>
          <div class="messageFooter">
            <span>{{ item.createdAt | resolvingDate }}</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="submitReme" @click="closeAnnouncementDialog">关闭</el-button>
      </span>
    </el-dialog>

    <!-- <MessageReminder
          @GetAllMessageListAsync="GetAllMessageListAsync"
          :userInfo="userInfo"
          :messageList="messageList"
        /> -->
  </div>
</template>

<script>
// import MessageReminder from './messageReminder.vue'
import { OverView } from '@/api/overView/service'
const heartCheck = {
    timeout: 30 * 1000,
    timer: null,
    serverTimer: null,
    reset() {
        this.timer && clearTimeout(this.timer)
        this.serverTimer && clearTimeout(this.serverTimer)
    },
    start(ws) {
    // console.log('心跳检测')
        this.reset()
        this.timer = setTimeout(() => {
            // console.log('发送心跳,后端收到后，返回一个心跳消息')
            // onmessage拿到返回的心跳就说明连接正常
            ws.send(JSON.stringify({ heart: 1 }))
            this.serverTimer = setTimeout(() => {
                // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
                ws.close()
            }, this.timeout)
        }, this.timeout)
    }
}
export default {
    name: 'Notice',
    components: {
    // MessageReminder,
    },
    computed: {
        connectText() {
            return this.$store.state.situation.connectText
        }
    },
    data() {
        return {
            accountOutLine: '',
            announcementDialogVisible: false,
            messageOutput: [],
            // 登录人信息
            userInfo: {},
            wsuri: `ws://${process.env.VUE_APP_BASE_WEBSCOKET}//websocket/`, // ws wss
            lockReconnect: false, // 连接失败不进行重连
            maxReconnect: 5, // 最大重连次数，若连接失败
            socket: null
        }
    },
    filters: {
        resolvingDate(date) {
            const d = new Date(date)
            const month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
            const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
            const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
            const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
            const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
            const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
            return times
        }
    },

    mounted() {
        this.$store.dispatch('situation/setCommentText')
        // this.GetAllAnnouncementListAsync()
        // setCommentText
        // this.getUserInfo()
    },
    methods: {
        /**
     * @description: 获取当前登陆人信息 初始化Webscoket通信方法
     */
        async getUserInfo() {
            try {
                const result = await OverView.UserGetUserInfoAsync()
                if (result.success) {
                    this.userInfo = result.data
                    this.initWebSocket()
                }
            } catch (err) {
                console.log(err)
            }
        },
        reconnect() {
            console.log('duanxia')
            if (this.lockReconnect || this.maxReconnect <= 0) {
                return
            }
            setTimeout(() => {
                // this.maxReconnect-- // 不做限制 连不上一直重连
                // this.initWebSocket()
            }, 30 * 1000)
        },
        initWebSocket() {
            try {
                if ('WebSocket' in window) {
                    this.wsuri = this.wsuri + this.userInfo.id
                    this.socket = new WebSocket(this.wsuri)
                    this.wsuri = `ws://${process.env.VUE_APP_BASE_WEBSCOKET}/websocket/`
                } else {
                    console.log('您的浏览器不支持websocket')
                }
                this.socket.onopen = this.websocketonopen
                this.socket.onerror = this.websocketonerror
                this.socket.onmessage = this.websocketonmessage
                this.socket.onclose = this.websocketclose
            } catch (e) {
                this.reconnect()
            }
        },
        websocketonopen() {
            console.log('WebSocket连接成功', this.socket.readyState)
            heartCheck.start(this.socket)
            // this.socket.send('发送数据')
            // this.websocketsend()
        },
        websocketonerror(e) {
            console.log('WebSocket连接发生错误', e)
            this.reconnect()
        },
        websocketonmessage(e) {
            console.log(e)
            const data = JSON.parse(e.data)
            console.log('得到响应', data)
            console.log('可以渲染网页数据...')
            // 消息获取成功，重置心跳
            heartCheck.start(this.socket)
        },
        websocketsend(data) {
            console.log(data)
            this.socket.send(data)
        },
        websocketclose(e) {
            console.log('connection closed (' + e.code + ')')
            this.reconnect()
        },
        closeAnnouncementDialog() {
            this.announcementDialogVisible = false
        },
        lookForAnnouncement() {
            this.announcementDialogVisible = true
            this.GetAllAnnouncementListAsync()
        },
        // announcementChange(val) {
        //     this.announcementDialogVisible = val
        // },
        async GetAllAnnouncementListAsync() {
            try {
                const result = await OverView.GetAllAnnouncementListAsync()
                if (result.success) {
                    this.messageOutput = result.data
                    if (this.messageOutput.length > 0) {
                        this.accountOutLine = this.messageOutput[0].announcementContent
                    }
                }
            } catch (err) {
                console.log(err)
            }
        }
        // async GetAllMessageListAsync() {
        //     try {
        //         const result = await OverView.GetAllMessageListAsync()
        //         if (result.success) {
        //             this.messageList = result.data
        //             console.log('消息提醒信息', result.data)
        //         }
        //     } catch (err) {
        //         console.log(err)
        //     }
        // }
    }
}
</script>

<style lang="scss" scoped>
.app-notice {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-avatar {
    background: #fff;
  }
  .marquee-container {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .notice-icons {
      width: 35px;
      height: 28px;
      margin-left: 20px;
    }
    .app-marquee {
      color: #606266;
      font-weight: 600;
    }
    .notice-btns {
      margin-left: 20px;
    }
  }
}
.commonbody {
  height: 500px;
  padding: 0 10px;
  overflow-y: scroll;
  /*滚动条样式*/
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px;
    height: 32px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    background: #ccc;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 0;
    background: transparent;
  }
}
::v-deep .commondialog {
  .el-dialog {
    border-radius: 5px;
    .el-dialog__body {
      border-bottom: 1px solid #cad0d8;
      border-top: 1px solid #cad0d8;
      padding: 10px 10px;

    }
  }
}

.messageReminderContent {
  width: 100%;
  min-height: 175px;
  padding: 10px;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
//   user-select: none;

  .messaageContent {
    width: 100%;
    font-size: 16px;
    box-sizing: border-box;
    height: 144px;
  }
  .messageFooter {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
    font-size: 17px;
    color: #666666;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

::v-deep .el-carousel__arrow {
  display: none;
}
</style>
